import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/sale_bid_project_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/sale_bid_project.dart';
import 'package:flutter_admin/pages/odoo/sale_bid_marketinfo/sale_bid_marketinfo_edit.dart';
import 'package:flutter_admin/pages/odoo/sale_bid_project/sale_bid_project_edit.dart';
import 'package:flutter_admin/pages/odoo/sale_bid_project/sale_bid_project_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/sale_bid_result/sale_bid_result_list.dart';
import 'package:flutter_admin/pages/odoo/sale_bid_result_manufactor/sale_bid_result_manufactor_list.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/dms_file/dms_file_list.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

// 招投标项目
class SaleBidProjectList extends StatefulWidget {
  SaleBidProjectList({Key? key}) : super(key: key);

  @override
  _SaleBidProjectListState createState() => _SaleBidProjectListState();
}

class _SaleBidProjectListState extends State<SaleBidProjectList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  SaleBidProject saleBidProject = SaleBidProject();
  List<SaleBidProject> selectedList = [];
  DateFormat format = DateFormat('yyyy-MM-dd');

  List<SelectOptionVO> projectcategoryList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    projectcategoryList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: '0', label: "市场部"),
      SelectOptionVO(value: '1', label: "海外部"),
      SelectOptionVO(value: '2', label: "其他"),
    ];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelect(
            width: 180,
            label: '项目类别',
            dataList: projectcategoryList,
            value: saleBidProject.projectcategory,
            onSaved: (v) => {saleBidProject.projectcategory = v},
          ),
          CryInput(
            width: 160,
            label: '项目编号',
            value: saleBidProject.projectcode,
            onSaved: (v) {
              saleBidProject.projectcode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '项目名称',
            value: saleBidProject.projectname,
            onSaved: (v) {
              saleBidProject.projectname = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '开标开始日期',
            value: saleBidProject.createDateStart,
            lastDate: isNotBlank(saleBidProject.createDateEnd)
                ? format.parse(saleBidProject.createDateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleBidProject.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              saleBidProject.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '开标结束日期',
            value: saleBidProject.createDateEnd,
            firstDate: isNotBlank(saleBidProject.createDateStart)
                ? format.parse(saleBidProject.createDateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              saleBidProject.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              saleBidProject.createDateEnd = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('项目类别')),
        DataColumn(label: Text('项目编号')),
        DataColumn(label: Text('项目名称')),
        DataColumn(label: Text('项目国别')),
        DataColumn(label: Text('省份')),
        DataColumn(label: Text('项目性质')),
        DataColumn(label: Text('客户名称')),
        DataColumn(label: Text('招标类别')),
        DataColumn(label: Text('招标代理名称')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('项目属性')),
        DataColumn(label: Text('项目规模/产品数量')),
        DataColumn(label: Text('项目预算(含税/万元)')),
        DataColumn(label: Text('购标截止时间')),
        DataColumn(label: Text('澄清截止时间')),
        DataColumn(label: Text('投标截止时间')),
        DataColumn(label: Text('开标日期')),
        DataColumn(label: Text('公示日期')),
        DataColumn(label: Text('交货日期')),
        DataColumn(label: Text('标书费(元)')),
        DataColumn(label: Text('投标保证金(元)')),
        DataColumn(label: Text('样品检测费(元)')),
        DataColumn(label: Text('招标代理服务费(元)')),
        DataColumn(label: Text('履约保证金(元)')),
        DataColumn(label: Text('评标办法')),
        DataColumn(label: Text('价格评标')),
        DataColumn(label: Text('招标方联系人（商务）')),
        DataColumn(label: Text('招标方联系方式（商务）')),
        DataColumn(label: Text('招标方联系人（技术）')),
        DataColumn(label: Text('招标方联系方式（技术）')),
        DataColumn(label: Text('有无二次议价机会')),
        DataColumn(label: Text('市场和项目情况介绍及客户基础技术要求')),
        DataColumn(label: Text('资质文件')),
        DataColumn(label: Text('样品要求')),
        DataColumn(label: Text('品牌专利要求')),
        DataColumn(label: Text('环保要求')),
        DataColumn(label: Text('包装要求')),
        DataColumn(label: Text('制标人')),
        DataColumn(label: Text('投标结果')),
        DataColumn(label: Text('价格判定')),
        DataColumn(label: Text('报价准确率')),
        DataColumn(label: Text('利润率')),
        DataColumn(label: Text('利润')),
      ],
      getCells: (m) {
        SaleBidProject saleBidProject = SaleBidProject.fromMap(m);
        return [
          DataCell(Text(saleBidProject.projectcategory == '0'
              ? '市场部'
              : saleBidProject.projectcategory == '1'
                  ? '海外部'
                  : saleBidProject.projectcategory == '2'
                      ? '其他'
                      : '--')),
          DataCell(Text(saleBidProject.projectcode ?? '--')),
          DataCell(Text(saleBidProject.projectname ?? '--')),
          DataCell(Text(saleBidProject.projectnation ?? '--')),
          DataCell(Text(saleBidProject.province ?? '--')),
          DataCell(Text(saleBidProject.projectnature == '0'
              ? '省采'
              : saleBidProject.projectnature == '1'
                  ? '铁塔'
                  : saleBidProject.projectnature == '2'
                      ? '电网'
                      : saleBidProject.projectnature == '3'
                          ? '广电'
                          : saleBidProject.projectnature == '4'
                              ? '政企'
                              : saleBidProject.projectnature == '5'
                                  ? '运营商'
                                  : '--')),
          DataCell(Text(saleBidProject.customername ?? '--')),
          DataCell(Text(saleBidProject.bidcategory == '0'
              ? '供货标'
              : saleBidProject.bidcategory == '1'
                  ? '总包标'
                  : '--')),
          DataCell(Text(saleBidProject.bidagency ?? '--')),
          DataCell(Text(saleBidProject.productname ?? '--')),
          DataCell(Text(saleBidProject.projectattribute == '0'
              ? '传统'
              : saleBidProject.projectattribute == '1'
                  ? '创新'
                  : '--')),
          DataCell(Text(saleBidProject.projectsize != null
              ? saleBidProject.projectsize.toString()
              : '--')),
          DataCell(Text(saleBidProject.projectbudget != null
              ? saleBidProject.projectbudget.toString()
              : '--')),
          DataCell(Text(saleBidProject.buydeadline ?? '--')),
          DataCell(Text(saleBidProject.clarifydeadline ?? '--')),
          DataCell(Text(saleBidProject.biddeadline ?? '--')),
          DataCell(Text(saleBidProject.openingdate ?? '--')),
          DataCell(Text(saleBidProject.publicitydate ?? '--')),
          DataCell(Text(saleBidProject.deliverydate ?? '--')),
          DataCell(Text(saleBidProject.tenderfee != null
              ? saleBidProject.tenderfee.toString()
              : '--')),
          DataCell(Text(saleBidProject.bidfree != null
              ? saleBidProject.bidfree.toString()
              : '--')),
          DataCell(Text(saleBidProject.checkfee != null
              ? saleBidProject.checkfee.toString()
              : '--')),
          DataCell(Text(saleBidProject.agencyservicefee ?? '--')),
          DataCell(Text(saleBidProject.performancebond ?? '--')),
          DataCell(Text(saleBidProject.bidmethod ?? '--')),
          DataCell(Text(saleBidProject.priceevaluation ?? '--')),
          DataCell(Text(saleBidProject.businesscontacts ?? '--')),
          DataCell(Text(saleBidProject.businesscontactsnumber ?? '--')),
          DataCell(Text(saleBidProject.technologycontacts ?? '--')),
          DataCell(Text(saleBidProject.technologycontactsnumber ?? '--')),
          DataCell(Text(saleBidProject.issecondbargaining == '0'
              ? '无'
              : saleBidProject.issecondbargaining == '1'
                  ? '有'
                  : '--')),
          DataCell(Text(saleBidProject.projectintroduction ?? '--')),
          DataCell(Text(saleBidProject.qualificationdocuments ?? '--')),
          DataCell(Text(saleBidProject.samplerequirements ?? '--')),
          DataCell(Text(saleBidProject.brandpatentrequirements ?? '--')),
          DataCell(Text(saleBidProject.environmentalrequirements ?? '--')),
          DataCell(Text(saleBidProject.packagingrequirements ?? '--')),
          DataCell(Text(saleBidProject.bidmaker ?? '--')),
          DataCell(Text(saleBidProject.bidresults == '0'
              ? '未中标'
              : saleBidProject.bidresults == '1'
                  ? '中标'
                  : '--')),
          DataCell(Text(saleBidProject.pricedetermination ?? '--')),
          DataCell(Text(saleBidProject.quotationaccuracy != null
              ? saleBidProject.quotationaccuracy.toString()
              : '--')),
          DataCell(Text(saleBidProject.profitmargin != null
              ? saleBidProject.profitmargin.toString()
              : '--')),
          DataCell(Text(saleBidProject.profit ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
          label: "复制",
          iconData: Icons.copy,
          onPressed:
              selectedList.length == 1 ? () => _copy(selectedList[0]) : null,
        ),
        CryButton(
          label: "市场信息",
          iconData: Icons.edit_attributes,
          onPressed: selectedList.length == 1
              ? () => _marketinfo(selectedList[0])
              : null,
        ),
        CryButton(
          label: "投标结果",
          iconData: Icons.edit_attributes,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        ),
        CryButton(
          label: "厂家详情",
          iconData: Icons.edit_attributes,
          onPressed: selectedList.length == 1
              ? () => _manufactorInfo(selectedList[0])
              : null,
        ),
        CryButton(
          label: '附件管理',
          iconData: Icons.view_agenda_rounded,
          onPressed:
              selectedList.length == 1 ? () => _dmsFile(selectedList[0]) : null,
        ),
        CryButton(
          label: "查看",
          iconData: Icons.view_headline,
          onPressed:
              selectedList.length == 1 ? () => _view(selectedList[0]) : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openDetail(SaleBidProject saleBidProject) {
    Utils.fullscreenDialog(SaleBidResultList(saleBidProject: saleBidProject));
  }

  _manufactorInfo(SaleBidProject saleBidProject) {
    Utils.fullscreenDialog(
        SaleBidResultManufactorList(saleBidProject: saleBidProject));
  }

  _copy(SaleBidProject? saleBidProject) async {
    saleBidProject!.id = null;
    SaleBidProjectOdooApi.copy(saleBidProject.toOdooMap())
        .then((ResponseBodyApi res) {
      if (!res.success!) {
        return;
      }
      _query();
      CryUtils.message('复制成功');
    });
  }

  _marketinfo(SaleBidProject? saleBidProject) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleBidMarketinfoEdit(
          saleBidProject: saleBidProject,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (saleBidProject == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _view(SaleBidProject? saleBidProject) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: SaleBidProjectEdit(
          saleBidProject: saleBidProject,
          isView: true,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (saleBidProject == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _edit(SaleBidProject? saleBidProject) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: SaleBidProjectEdit(
          saleBidProject: saleBidProject,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (saleBidProject == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _dmsFile(SaleBidProject saleBidProject) {
    UdtTbDocmentstock? udtTbDocmentstock;
    Utils.fullscreenDialog(DmsFileList(
        udtTbDocmentstock: udtTbDocmentstock, saleBidProject: saleBidProject));
  }

  _reset() {
    saleBidProject = SaleBidProject();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await SaleBidProjectOdooApi.page(
        data: {"page": page, "domainList": saleBidProject.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<SaleBidProject> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await SaleBidProjectOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleBidProjectDialog(),
      ),
    ).then((v) {
      if (v != null) {
        saleBidProject = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<SaleBidProject>((e) => SaleBidProject.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.dmsFile) {
          _dmsFile(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete),
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('附件管理'),
          ),
        ),
      ],
    );
  }
}
